const puppeteer = require("puppeteer-extra");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");
puppeteer.use(StealthPlugin());
const dayjs = require("dayjs");
const axios = require("axios");
const userDataDir = process.env.WEB_CONFIG_USER_DATA_DIR;
const executablePath = process.env.WEB_CONFIG_EXECUTABLE_PATH;
const logger = require("../../utils/logger");

const BEIJINGHAO_USERNAME = process.env.BAIJIAHAO_USERNAME;
const BEIJINGHAO_PASSWORD = process.env.BAIJIAHAO_PASSWORD;

async function getArticlesInfo(params) {
  let results = [];
  const browser = await puppeteer.launch({
    headless: false,
    userDataDir,
    executablePath,
    defaultViewport: null,
    args: [
      "--no-sandbox",
      "--disable-setuid-sandbox",
      "--disable-features=site-per-process",
      "--start-maximized",
      // "--auto-open-devtools-for-tabs",
    ],
    ignoreHTTPSErrors: true,
  });
  try {
    const page = await browser.newPage();
    // 设置窗口全屏，计算窗口尺寸
    const dimensions = await page.evaluate(() => ({
      width: window.innerWidth,
      height: window.innerHeight,
    }));
    await page.setViewport(dimensions);
    await page.goto(
      "https://baijiahao.baidu.com/builder/theme/login?theme=beijing",
      { waitUntil: "networkidle2" }
    );

    if (await isNotLogin(page)) {
      logger.info("未登录，等待用户登录...");
      // 实现北京号的登录逻辑
      await login(page);
    }

    logger.info("已登录");

    await page.waitForSelector(".mp-aside");
    await page.goto(
      "https://baijiahao.baidu.com/builder/rc/analysiscontent/single",
      { waitUntil: "networkidle2" }
    );
    // 输入日期，加载指定日期列表
    await handleDate(page, params);
    //获取所有的文章列表

    results = await fetchArticles(page, params);
    logger.info(`获取 ${results.length} 条数据`);
    // 通过data_url获取详细的数据
    results = await fetchArticleDetail(page, results);
    return results;
  } catch (error) {
    logger.error(`发生错误: ${error.message}`);
    return [];
  } finally {
    await browser.close();
  }
}

async function isNotLogin(page) {
  // 实现检查北京号是否登录的逻辑，如果存在input value=“登录” 则未登录
  const input = await page.$('input[value="登录"]');
  return !!input;
}

// 实现北京号的登录逻辑
async function login(page) {
  await page.evaluate(() => {
    const loginLink = document.querySelector(".pass-sms-link-back");
    if (loginLink) {
      loginLink.click();
    }
  });
  // 等待用户名输入框
  const userNameInput = await page.waitForSelector(".pass-text-input-userName");
  if (userNameInput) {
    await userNameInput.type(BEIJINGHAO_USERNAME, { delay: 100 });
  }
  // 等待密码输入框
  const passwordInput = await page.waitForSelector(".pass-text-input-password");
  if (passwordInput) {
    await passwordInput.type(BEIJINGHAO_PASSWORD, { delay: 100 });
  }
  await new Promise((resolve) => setTimeout(resolve, 1000));
  // 等待登录按钮
  await page.evaluate(() => {
    const loginButton = document.querySelector(".pass-button-submit");
    if (loginButton) {
      loginButton.click();
    }
  });
}
// 实现日期输入
async function handleDate(page, params) {
  // 实现日期输入的逻辑
  const selectDate = await page.waitForSelector(
    ".client_components_selectDate"
  );
  if (selectDate) {
    selectDate.click();
    logger.info("点击了日期选择器");
  }
  const { start_day, end_day } = calculateDateRange(params);
  const startDateInput = await page.waitForSelector(
    `.ant-calendar-range-left input`
  );
  if (startDateInput) {
    //先清空
    await startDateInput.evaluate((el) => (el.value = ""));
    await new Promise((resolve) => setTimeout(resolve, 2000));
    await startDateInput.type(start_day, { delay: 100 });
    logger.info(`输入开始日期: ${start_day}`);
  }
  await new Promise((resolve) => setTimeout(resolve, 1000));
  if (selectDate) {
    selectDate.click();
    logger.info("点击了日期选择器");
  }
  const endDateInput = await page.waitForSelector(
    `.ant-calendar-range-right input`
  );
  if (endDateInput) {
    await endDateInput.evaluate((el) => (el.value = ""));
    await new Promise((resolve) => setTimeout(resolve, 2000));
    await endDateInput.type(end_day, { delay: 100 });
    logger.info(`输入结束日期: ${end_day}`);
  }
  await new Promise((resolve) => setTimeout(resolve, 3000));
}
// 计算开始和结束日期
function calculateDateRange(params) {
  // 实现日期计算的逻辑
  if (params.update_type === "highFrequency") {
    // 高频任务最近7天
    const end_day = dayjs().format("YYYY/MM/DD");
    const start_day = dayjs().subtract(7, "day").format("YYYY/MM/DD");
    return { start_day, end_day };
  } else {
    // 其它任务，默认最近30天
    const end_day = dayjs().format("YYYY/MM/DD");
    const start_day = dayjs().subtract(59, "day").format("YYYY/MM/DD");
    return { start_day, end_day };
  }
}
// 获取文章列表
async function fetchArticles(page, params) {
  // 实现获取北京号文章列表的逻辑
  // 没有数据
  const noData = await page.evaluate(() => {
    const placeholder = document.querySelector(".ant-table-placeholder");
    return !!placeholder;
  });
  if (noData) {
    logger.info("没有数据");
    return [];
  }
  // 1页数据
  const noNextPage = await page.evaluate(() => {
    const nextPage = document.querySelector(".ant-pagination");
    return !nextPage;
  });
  if (noNextPage) {
    const currentPageData = await getCurrentPageData(page);
    logger.info(`只有1页数据, ${currentPageData.length} 条`);
    return currentPageData;
  }
  let allData = [];
  let pageNumber = 1;

  while (true) {
    // 获取当前页数据
    const currentPageData = await getCurrentPageData(page);
    allData = allData.concat(currentPageData);

    logger.info(
      `第 ${pageNumber} 页，获取 ${currentPageData.length} 条数据，累计 ${allData.length} 条数据`
    );

    // 检查是否有可点击的下一页
    const hasNextPage = await page.evaluate(() => {
      const nextPageButton = document.querySelector(".ant-pagination-next");
      return (
        nextPageButton &&
        nextPageButton.getAttribute("aria-disabled") === "false"
      );
    });

    if (!hasNextPage) {
      logger.info(`已经是最后一页（第 ${pageNumber} 页）`);
      break;
    }

    // 点击下一页
    await page.click(".ant-pagination-next");
    await page.waitForSelector(".ant-table-tbody", { timeout: 15000 });
    await new Promise((resolve) => setTimeout(resolve, 2000)); // 等待页面加载

    pageNumber++;
    logger.info(`正在加载第 ${pageNumber} 页...`);
  }

  logger.info(`共获取 ${allData.length} 条数据，总共 ${pageNumber} 页`);
  return allData;
}
// 获取当前页数据
async function getCurrentPageData(page) {
  try {
    const currentPageData = await page.evaluate(() => {
      const trs = document.querySelectorAll(".ant-table-tbody tr");
      return Array.from(trs).map((tr) => {
        const tds = tr.querySelectorAll("td");
        const obj = {};
        const contentType = {
          视频: "video",
          图集: "gallery",
          图文: "news",
        };
        Array.from(tds).forEach((td, index) => {
          if (index === 0) {
            const link = td.querySelector("a");
            if (link) {
              obj.title = link.innerText;
              obj.url = link.href;
            }
          } else if (index === 1) {
            obj.content_type = contentType[td.innerText] || "unknown";
          } else if (index === 2) {
            obj.publish_time = td.innerText;
          } else if (index === 3) {
            obj.read_count = Number(td.innerText);
          } else if (index === 4) {
            obj.comment_count = Number(td.innerText);
          } else if (index === 5) {
            const link = td.querySelector("a");
            if (link) {
              obj.data_url = link.href;
            }
          }
        });
        return obj;
      });
    });
    logger.info(`成功获取当前页面数据，共 ${currentPageData.length} 条`);
    return currentPageData;
  } catch (error) {
    logger.error(`获取当前页面数据时发生错误: ${error.message}`);
    return [];
  }
}
// 获取文章详情
async function fetchArticleDetail(page, results) {
  if (results.length === 0) {
    return [];
  }

  const detailedResults = [];

  for (const article of results) {
    try {
      let articleDetail = null;

      const responseHandler = async (response) => {
        if (
          response
            .url()
            .includes(
              "https://baijiahao.baidu.com/author/eco/statistics/ArticleStatistic"
            )
        ) {
          articleDetail = await response.json();
        }
      };

      page.on("response", responseHandler);

      // 访问文章详情页
      await page.goto(article.data_url, {
        waitUntil: "networkidle0",
        timeout: 30000,
      });

      // 等待一段时间确保数据加载完成
      await new Promise((resolve) => setTimeout(resolve, 3000));

      if (articleDetail) {
        // 合并原有数据和详细数据
        detailedResults.push({
          ...article,
          id: articleDetail?.data?.article_id,
          read_count: articleDetail?.data?.view_count || 0,
          recommend_count: articleDetail?.data?.recommend_count || 0,
          like_count: articleDetail?.data?.likes_count || 0,
          collect_count: articleDetail?.data?.collect_count || 0,
          comment_count: articleDetail?.data?.comment_count || 0,
          share_count: articleDetail?.data?.share_count || 0,
          complete_read_rate:
            articleDetail?.data?.complete_rate > 0
              ? articleDetail?.data?.complete_rate + "%"
              : 0 + "%",
          publish_time: articleDetail?.data?.publish_time,
        });
        logger.info(`成功获取文章 "${article.title}" 的详细数据`);
      } else {
        logger.warn(`未能获取文章 "${article.title}" 的详细数据`);
        detailedResults.push(article);
      }
      // 控制访问频率，等待3-5秒
      await new Promise((resolve) =>
        setTimeout(resolve, 3000 + Math.random() * 2000)
      );
    } catch (error) {
      logger.error(`处理文章 "${article.title}" 时发生错误: ${error.message}`);
      detailedResults.push(article);
    }
  }

  return detailedResults;
}
// ... 其他辅助函数 ...

exports.handleCommand = async (command, params) => {
  switch (command) {
    case "getArticlesInfo":
      const data = await getArticlesInfo(params);
      return { data };
    default:
      throw new Error("不支持的命令");
  }
};
